package com.sj.tensquare.web.config;

import com.sj.tensquare.web.pojo.User;
import com.sj.tensquare.web.server.LoginServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author sj
 * @date 2020/12/8 - 10:53
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
//    @Autowired
    private LoginServer userService;
    private Logger logger = LoggerFactory.getLogger(getClass());
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.debug("执行了=>授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到user用户

        info.addStringPermission("succeed");//获取对应的权力

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.debug("执行了=>认证");
        //用户名，密码 数据库中取
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //获取用户信息
        User user = userService.queryByName(userToken.getUsername());

        if (user==null){//数据库查无此人
            return null;//抛出异常 UnknownAccountException
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("username",user.getLoginUserName());
        //密码认证shiro做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}